//显示文本
import * as THREE from 'three';
//import { FontLoader } from '../../../node_modules/three/examples/jsm/loaders/FontLoader.js';
import TWEEN from '../../../node_modules/three/examples/jsm/libs/tween.module.js';

class showText{ 
    constructor(text,x,y,color,textSize,scene,font){
        
        this.text = text;
        this.x=x;
        this.y=y;
        this.color=color;
        this.textSize = textSize;
        this.scene = scene;
        this.font=font;

        this.z=0;
        this.createText();
        this.width=0;
        this.opacity={v:0}; // 初始透明度为0
        this.newPos={x:x,y:y};//移动目标位置
    }
    createText(){
        //计算文字长度
        this.material = new THREE.MeshBasicMaterial({ color: this.color });
        //console.log('this.font----------=',this.font)
        const shapes = this.font.generateShapes( this.text, this.textSize);
        const geometry = new THREE.ShapeGeometry( shapes );
        geometry.computeBoundingBox();
        const xMid = - 0.5 * ( geometry.boundingBox.max.x - geometry.boundingBox.min.x );
        this.width=0;//geometry.boundingBox.max.x;
        //平移到中心
        //geometry.translate( xMid+this.x, this.y, 0 );
        this.material.transparent=true; 
        this.material.opacity=0;//所有文字刚加载时不显示，要显示时调用fadeIn
        this.text_mesh = new THREE.Mesh( geometry,this.material );
        this.text_mesh.position.x=xMid+this.x;
        this.text_mesh.position.y=this.y;
        this.scene.add( this.text_mesh );
        console.log(this.text+",length="+this.width);
    }
    
   // 创建淡入动画
   fadeIn(callBack){
     new TWEEN.Tween(this.opacity)
      .to( {v:1} , 2000) // 2秒内透明度从0变为1
      .onUpdate(() => {
        this.material.opacity = this.opacity.v; // 更新材质透明度
     })
      .onComplete(() => {
        if(callBack){callBack();}
     })
     .start();
    }
    // 创建淡出动画
    fadeOut(callBack){
    new TWEEN.Tween(this.opacity)
    .to( {v:0} , 2000) // 2秒内透明度从1变为0
    .onUpdate(() => {
        this.material.opacity = this.opacity.v; // 更新材质透明度
    })
    .onComplete(() => {
        if(callBack){callBack();}
    })
    .start();
    }

    //移动
    moveTo(tox,toy,callBack){
        console.log('text move to',tox, toy)
    new TWEEN.Tween(this.newPos)
    .to( {x:tox,y:toy} , 2000) // 2秒内透明度从1变为0
    //console.log('typeof text mesh',typeof(this.text_mesh))
    .onUpdate(() => {
        //console.log(this.newPos.x, this.newPos.y)
        this.x = this.newPos.x
        this.y = this.newPos.y
        this.text_mesh.position.x=this.x;
        this.text_mesh.position.y=this.y;
        this.text_mesh.position.z=0;
        
    })
    .onComplete(() => {
        console.log('text move to complete',callBack)
        if(callBack){callBack();}
    })
    .start();
    }

    removeMe(){
        //this.removeFromParent(); //淡出之后删除
    }

}

export default showText;